package com.jpz.controller;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jpz.bean.Emp;
import com.jpz.bean.Grade;
import com.jpz.bean.Loginlog;
import com.jpz.bean.Permission;
import com.jpz.bean.Role;
import com.jpz.bean.Student;
import com.jpz.bean.User;
import com.jpz.bean.UserRole;
import com.jpz.service.EmpService;
import com.jpz.service.GradeService;
import com.jpz.service.LoginlogService;
import com.jpz.service.PermissionService;
import com.jpz.service.RoleService;
import com.jpz.service.StudentService;
import com.jpz.service.UserRoleService;
import com.jpz.service.Userservice;
import com.jpz.utils.pageshow;

import net.sf.jsqlparser.statement.select.Select;

@RequestMapping("/user")
@Controller
public class Usercontroller {
	@Autowired
	Userservice userservice;
	@Autowired
	LoginlogService loginlogservice;
	@Autowired
	EmpService empservice;
	@Autowired
	GradeService gradeservice;
	@Autowired 
	StudentService studentservice;
	@Autowired
	PermissionService permission;
	@Autowired
	RoleService rs;
	@Autowired
	UserRoleService urs;
	@RequestMapping("/login")

	public void login(Model model,String username,String password,HttpServletRequest request,HttpServletResponse response) {
		
		User user = userservice.selectOne(new EntityWrapper<User>().eq("username", username).eq("password", password).eq("del", 0));
		if(user!=null) {
			HttpSession session = request.getSession();
			//获取当前时间
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = format.format(new Date());
			//获取IP地址
			try {
				String add = InetAddress.getLocalHost().getHostAddress().toString();
				Loginlog loginlog = new Loginlog(add, user.getUsername(), date, "成都");
				//将时间和IP存入日志文件中
				boolean insert = loginlogservice.insert(loginlog);
				//将时间 ip 更新
				user.setIp(add);
				user.setLastlogintime(date);
				userservice.updateById(user);
				//查询菜单
				List<Permission> mlist = permission.getmymenus(user.getId());
				//将菜单存入session中带到页面进行显示
				session.setAttribute("menu", mlist);
			} catch (UnknownHostException e1) {
				e1.printStackTrace();
			}
			session.setAttribute("user", user);
			try {
				response.getWriter().write("<script>location.href='/Dida/index.jsp';</script>");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else {
			try {
				response.setContentType("text/html;charset=utf-8");
				response.getWriter().write("<script>alert('账号或密码错误！');location.href='/Dida/login.jsp';</script>");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	@RequestMapping("/logout")
	public String logout(Model model,HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.invalidate();
		return "redirect:/login.jsp";
	}

	@RequestMapping("/upmima")
	public void gaibianmima(Integer uid,String nmima,HttpServletResponse response) {
		System.out.println("从前端获取的用户id"+uid);
		System.out.println("从前端获取的密码"+nmima);
		User user = userservice.selectById(uid);
		System.out.println("查询出来的用户"+user);
		user.setPassword(nmima);
		userservice.updateById(user);
		try {
			response.getWriter().write("<script>alert('密码修改成功 即将跳转到登录界面');parent.location.href='/Dida/login.jsp'</script>");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/myinfo")
	public String mymassage(int uid,Model model) {
		Object user = userservice.selectById(uid);
		model.addAttribute("user", user);
		return "/userInfo.jsp";
	}
	@RequestMapping("/pic")
	public String pic(int uid,Model model) {
		User user = userservice.selectById(uid);
		model.addAttribute("user", user);
		return "/photo.jsp";
	}
	@RequestMapping("/main")
	public String main(Model model,String uname) {
		//按照时间的降序排列 获取前四个
		Wrapper<Loginlog> wrapper = new EntityWrapper<Loginlog>().eq("no", uname).orderBy("createtime",false);
		Page<Loginlog> page = new Page<Loginlog>(1, 4);
		Page<Loginlog> page2 = loginlogservice.selectPage(page, wrapper);
		List<Loginlog> list = page2.getRecords();
		//统计出班级  学员  员工人数
		int gradecount = gradeservice.selectCount(new EntityWrapper<Grade>().eq("del", 0));
		int stucount = studentservice.selectCount(new EntityWrapper<Student>().eq("del", 0));
		int empcount = empservice.selectCount(new EntityWrapper<Emp>().eq("del", 0));
		model.addAttribute("gradecount", gradecount);
		model.addAttribute("stucount", stucount);
		model.addAttribute("empcount", empcount);
		model.addAttribute("llist", list);
		return "/main.jsp";
	}
	@RequestMapping("/show")
	public String showlist(Integer pageindex,User user,Model model) {
		System.out.println("获取的user"+user);
		Page<User> results = null;
		// 分页工具
		Page<User> page = new Page<User>(pageindex, 4);
		EntityWrapper<User> entityWrapper = new EntityWrapper<User>();
		// 查询的数据结果集对象
		if (user != null && user.getUsername() != null) {
			entityWrapper.eq("del", 0).like("username", user.getUsername());
		}
		
		if (user != null && user.getLocked() != null && !user.getLocked().equals("-1")) {
			entityWrapper.eq("del", 0).eq("locked", user.getLocked());
		}
		results = userservice.selectPage(page, entityWrapper);
		// 获取总数
		int totalCount = ((Long) results.getTotal()).intValue();
		
		// 查询到每页数据
		List<User> users = results.getRecords();
		for (User user2 : users) {
			System.out.println("获取的user"+user2);
		}
		for (User user2 : users) {
			Integer id = user2.getId();
		//	List<UserRole> list = userservice.selectList(new EntityWrapper<UserRole>().eq("sys_user_id", id));
			List<UserRole> list = urs.selectList(new EntityWrapper<UserRole>().eq("sys_user_id", id));
			ArrayList<Role> m = new ArrayList<Role>();
			for (UserRole userRole : list) {
				Role role = rs.selectById(userRole.getSysRoleId());
				m.add(role);
			}
			user2.setRoles(m);
		}
		// 查询出所有班级
		//PageHelper<User> pageHelper = new PageHelper<User>(totalCount, pageIndex, pageSize, users, u);
		pageshow<User> pagebean = new pageshow<>(users, totalCount, user,results.getCurrent());
		model.addAttribute("pagebean", pagebean);
		
		return "/userlist.jsp";
		
	}
	@ResponseBody
	@RequestMapping("/toupdate")
	public Map<String, Object> toupdate(Integer uid) {
		User user = userservice.selectById(uid);
		System.out.println("查询对象是：" + user);
		List<Role> roles = rs.selectList(new EntityWrapper<Role>().eq("available", 1));
		for (Role role : roles) {
			int count = urs.selectCount(new EntityWrapper<UserRole>().eq("sys_user_id", uid).eq("sys_role_id", role.getId()));
			if (count > 0) {
				role.setFlag(true);
			}
		}
		Map<String, Object> map = new HashMap<>();
		map.put("user", user);
		map.put("roles", roles);
		return map;
	}
	@ResponseBody
	@RequestMapping("/update")
	public boolean update(User user, Integer[] rids) {
		return userservice.update(user, rids);
	}
}
